package com.standardoperationapp.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.standardoperationapp.R;
import com.standardoperationapp.app.BaseApplication;
import com.standardoperationapp.bean.CheckCodeBean;
import com.standardoperationapp.bean.LoginBean;
import com.standardoperationapp.global.Base64Utils;
import com.standardoperationapp.global.GsonUtils;
import com.standardoperationapp.global.RSAUtilsa;
import com.standardoperationapp.global.SharedPreferencesUtils;
import com.standardoperationapp.net.BaseSubscribe;
import com.standardoperationapp.net.OnSuccessAndFaultListener;
import com.standardoperationapp.net.OnSuccessAndFaultSub;
import com.standardoperationapp.utils.ToastUtil;

import java.io.Serializable;
import java.security.PublicKey;
import java.util.HashMap;

import io.reactivex.annotations.NonNull;


public class LoginActivity extends AppCompatActivity {
    private CheckBox checkbox;
    private CheckBox checkboxrfid;
    private Button loginbtn;
    private EditText usernameEdit;
    private EditText passwordEdit;
    private EditText codeEdit;
    private  ImageView codeImage;
    private TextView getCodeTv;
    private String uuid ="";
    private static String PUCLIC_KEY  = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQClDvYy8/9TtotqQsElqvGaggz/sjvFi3DHd2PJq3L1MEZJMGhx65vFiClAMfvqY/UiN7Uel9JQeSVCv7z33c6A5gqPSzWyZ8Fmg2CYwJrahYCnW8mkIDqdLsduKYy4UN4gds62bsiylkVeb8tzKOkriFVX3514Von6XFNHQPM5iwIDAQAB";
    @SuppressLint("MissingInflatedId")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        checkbox = (CheckBox) findViewById(R.id.checkbox);
        checkboxrfid = (CheckBox) findViewById(R.id.checkbox2);
        loginbtn =(Button) findViewById(R.id.login);
        usernameEdit =(EditText) findViewById(R.id.login_username);
        passwordEdit = (EditText)findViewById(R.id.login_password);
        codeEdit= (EditText)findViewById(R.id.login_code_ET);
        codeImage =(ImageView)findViewById(R.id.login_codeImage);
        getCodeTv=(TextView)findViewById(R.id.login_getCode_Tv) ;

        String loginNo = SharedPreferencesUtils.getSharedPreferencesData(BaseApplication.app, "username");
        String password = SharedPreferencesUtils.getSharedPreferencesData(BaseApplication.app, "password");
        boolean userRfid = SharedPreferencesUtils.getBooleanSharedPreferencesData(BaseApplication.app, "userRfid", true);

        if (userRfid) {
            checkboxrfid.setChecked(true);
        } else {
            checkboxrfid.setChecked(false);
        }
        if (password != null && !password.isEmpty()) {
            checkbox.setChecked(true);
        }
        usernameEdit.setText(loginNo);
        passwordEdit.setText(password);
//        usernameEdit.setText("zjh");
//        passwordEdit.setText("123!@#abcA");
        getCodeTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                String image="/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAAkAG8DASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWm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ZQrkA8AgHvz6HI9cUbWBU06MBFa1dCstuyAgKf7wyckLwcHBJJxWjA7unzMr8kh0XapGTgYyTkDGfX9Apu7bLSsrdR4ijDhxGgcAgNjkAkE/mQCfpUFvcvLctGwXaIY5OPVi2f8A0EUUVHX5f5D7HK3Gr3s3iA2aS/Z4jObc+SMEgsF3c5+bAHPbHFdTZ6ba2OTDHmRvvyudzue5JPrjPpRRVCRbooopDCiiigAooooAqXGm21xIZSrRzEY82JijfmOv41znh7Urq8uzDcSb1JwMfLt4J4AwOqjt6+tFFMT3NMXrxaxZW6IgjuoZHkGD1VkAxzjox/IVZeU2l0Y4gAh/hPQcdqKKkS3Z/9k=";
//                byte[] decode = Base64.decode(image, Base64.DEFAULT);
//                Bitmap bitmap = BitmapFactory.decodeByteArray(decode, 0, decode.length);
//                codeImage.setImageBitmap(bitmap);
                getCAPTCHA();
            }
        });
        loginbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String code =codeEdit.getText().toString();
                if(code.isEmpty()) {
//                    if (!SharedPreferencesUtils.getSharedPreferencesData(BaseApplication.app, "token").isEmpty()) {
//                        Intent intent = new Intent(LoginActivity.this,MainActivity.class);
//                        startActivity(intent);
//                        return;
//                    }

                      Toast.makeText(LoginActivity.this,"请输入验证码！",Toast.LENGTH_LONG).show();
                      return;
                }
                try {
                    //测试环境，自有登录
                    // 从字符串中得到公钥
                    PublicKey publicKey = RSAUtilsa.loadPublicKey(PUCLIC_KEY);
                    // 加密
                    byte[] encryptByte = RSAUtilsa.encryptData(passwordEdit.getText().toString().getBytes(), publicKey);
                    // 为了方便观察吧加密后的数据用base64加密转一下，要不然看起来是乱码,所以解密是也是要用Base64先转换
                    String afterencrypt = Base64Utils.encode(encryptByte);
                    getLogin(code,uuid,afterencrypt);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
        requestPermission();
    }

    /**
     * 申请动态权限
     */
    private void requestPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.SYSTEM_ALERT_WINDOW) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.VIBRATE) != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(this,
                    new String[]{
                            Manifest.permission.CAMERA,
                            Manifest.permission.ACCESS_FINE_LOCATION,
                            Manifest.permission.ACCESS_COARSE_LOCATION,
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.SYSTEM_ALERT_WINDOW,
                            Manifest.permission.VIBRATE
                    },
                    100);
        }
    }

    /**
     * 用户选择是否开启权限操作后的回调；TODO 同意/拒绝
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 100) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            } else {
                ToastUtil.showToast("权限申请被拒绝");
                Log.d("HL", "权限申请拒绝!");
            }
        }
    }

   public void getCAPTCHA()
   {

          BaseSubscribe.getCAPTCHA(this,  new OnSuccessAndFaultSub(new OnSuccessAndFaultListener() {
              @Override
              public void onSuccess(Object result) {
                  CheckCodeBean checkBean = GsonUtils.fromJson(result.toString(), CheckCodeBean.class);
                 String image =checkBean.getImg();
              //    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yKsO5o1GNjMSfwJ/rXK6wsNrr9pfYkMHmAyFi2QwOTyeehHHTjHQYrcbw3pDMWNmMn0dh/WnHw/pjRshtyQTnmRjz68mlCXK7hJNqxS1m9sv7NnIMXmzL8vlnLOxGM9ORgDmn6TEtvpw0y8EUhaLdJbsNx2PnqvcHDDHsaI/C9vbTrPazyJIrZHmKrgD2GBz781O91qVuGF5Y+fGORLZnkeg2nnP0qpSW0QSd7so6npMszw6nZlrS5KgtGxGQcdPlyMjnOCRTrTSZbcm+vp1uW2FSEzhVIwcdM1et7q11CAiGbfGrBm8pmQqQcggDBwSOQf1BrLvLTVZbqe2BEVnIckoQd68cLxn3x7nkjFJSb0JkuqLXhZJho0ZDKEMzEhlzuXGOOeOfr0PrkasUwK74o5TGcHa0ZQrkA8AgHvz6HI9cUbWBU06MBFa1dCstuyAgKf7wyckLwcHBJJxWjA7unzMr8kh0XapGTgYyTkDGfX9Apu7bLSsrdR4ijDhxGgcAgNjkAkE/mQCfpUFvcvLctGwXaIY5OPVi2f8A0EUUVHX5f5D7HK3Gr3s3iA2aS/Z4jObc+SMEgsF3c5+bAHPbHFdTZ6ba2OTDHmRvvyudzue5JPrjPpRRVCRbooopDCiiigAooooAqXGm21xIZSrRzEY82JijfmOv41znh7Urq8uzDcSb1JwMfLt4J4AwOqjt6+tFFMT3NMXrxaxZW6IgjuoZHkGD1VkAxzjox/IVZeU2l0Y4gAh/hPQcdqKKkS3Z/9k=";
                  byte[] decode = Base64.decode(image, Base64.DEFAULT);
                  Bitmap bitmap = BitmapFactory.decodeByteArray(decode, 0, decode.length);
                  codeImage.setImageBitmap(bitmap);
                  uuid= checkBean.getUuid();
                 // Glide.with(LoginActivity.this).load(bitmap).into(codeImage);

              }

              @Override
              public void onFault(String errorMsg) {
                  Toast.makeText(LoginActivity.this,"申请验证码失败！"+errorMsg,Toast.LENGTH_LONG).show();
              }
          }
        ));
   }

    public  void getLogin(String code,String uuid,String afterencrypt) {

       // String username="admin";
       // String password = "Su2YGrX+pT1DABFC6Ut5bruwGR9jMcMTD0jm+nv2bAbPxK7hjOdcIGP0NLJcRn5adSovbgw3gzXMSdHhcgG4JpZ5KYOcB5pvye9gUJYtbe7txA0scfMFWoYR62lTq7tSQXupxY3uKHbfDTH/1MOx1QIzGhT/4GIbT6rNuehWsYE=";
      Log.e("syj",afterencrypt);
       HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("username",usernameEdit.getText().toString());
       hashMap.put("password", afterencrypt);
      //  String code1= "j9kf";
        //String uuid1= "091157be663d43d3b2d816570cd7ea85";
       // hashMap.put("username",username);
       // hashMap.put("password", password);
        hashMap.put("code", code); //上一步的
        hashMap.put("uuid",uuid );
        BaseSubscribe.getLogin(this, hashMap, new OnSuccessAndFaultSub(new OnSuccessAndFaultListener() {
            @Override
            public void onSuccess(Object result) {
                LoginBean  bean = GsonUtils.fromJson(result.toString(), LoginBean.class);

                if (checkbox.isChecked()) {
                    SharedPreferencesUtils.setSharedPreferencesData(LoginActivity.this, "username", usernameEdit.getText().toString());
                    SharedPreferencesUtils.setSharedPreferencesData(LoginActivity.this, "password", passwordEdit.getText().toString());
                } else {
                    SharedPreferencesUtils.setSharedPreferencesData(LoginActivity.this, "username", "");
                    SharedPreferencesUtils.setSharedPreferencesData(LoginActivity.this, "password", "");

                }
                if (checkboxrfid.isChecked()) {
                    SharedPreferencesUtils.setSharedPreferencesData(BaseApplication.app, "userRfid", true);
                } else {
                    SharedPreferencesUtils.setSharedPreferencesData(BaseApplication.app, "userRfid", false);
                }

                SharedPreferencesUtils.setSharedPreferencesData(LoginActivity.this,"token",bean.getData().getAccess_token());

                Intent intent = new Intent(LoginActivity.this,MainActivity.class);
                startActivity(intent);
            }

            @Override
            public void onFault(String errorMsg) {
                Toast.makeText(LoginActivity.this,"验证码错误！"+errorMsg,Toast.LENGTH_LONG).show();

            }
        }

     ));
}


}
